<template>
  <Modal
    :visible="showLocalFlexSetting.show && showLocalFlexSetting.type == 0"
    :title="$t('FridgeFreezer.FlexCompartment.NewModeTitle.Text')"
    :cancel-text="$t('APP.Common.Ignore.Text')"
    :ok-text="$t('APP.Common.Apply.Text')"
    @ok="confirmFlex"
    @cancel="cancelFlex"
  >
    <view
      >{{
        brand == 'SIEMENS'
          ? isSmartHygieneLite
            ? $t('FridgeFreezer.SIEMENS.IsSmartHygieneLite.Text')
            : $t('FridgeFreezer.SIEMENS.NotSmartHygieneLite.Text')
          : $t('FridgeFreezer.BOSCH.CommonSmartHygieneLite.Text')
      }}){{ $t('FridgeFreezer.FlexCompartment.Add.Text') }}“{{ showLocalFlexSetting.newLocalFlexMode.modelName }}”{{
        $t('FridgeFreezer.FlexCompartment.Mode.Text')
      }}</view
    >
    <view>{{ showLocalFlexSetting.newLocalFlexMode.description }}</view>
  </Modal>
  <Modal
    :visible="showLocalFlexSetting.show && showLocalFlexSetting.type === 1"
    :title="$t('FridgeFreezer.FlexCompartment.ReplaceTitle.Text')"
    :cancel-text="$t('APP.Common.Cancel.Text')"
    :ok-text="$t('APP.Common.Confirm.Text')"
    @ok="confirmFlex"
    @cancel="cancelFlex"
  >
    <view
      >{{ $t('FridgeFreezer.FlexCompartment.Replace.Text') }}{{ localMode?.modelName
      }}{{ $t('FridgeFreezer.FlexCompartment.Mode.Text') }}</view
    >
  </Modal>
  <Modal
    :visible="showLocalFlexSetting.show && showLocalFlexSetting.type === 2"
    :title="$t('APP.Common.Remind.Text')"
    :ok-text="$t('APP.Common.ISee.Text')"
    @ok="confirmFlex"
    @cancel="cancelFlex"
  >
    <view>
      <text v-if="showLocalFlexSetting.newLocalFlexMode.modelName"
        >“{{ showLocalFlexSetting.newLocalFlexMode.modelName }}”</text
      >
      <text>{{ $t(showLocalFlexSetting.content) }}</text>
    </view>
  </Modal>
</template>
<script setup lang="ts">
import type { FridgeFreezerController, FridgeSettingGroup } from '@/controller/FridgeFreezer/definition'
import Modal from '@/common/modal.vue'
import { setSetting } from '@/api/appliance'
import { FLEX_KEY, FLEX_MODE_CUSTOM, FLEX_MODE_KEY } from '@/constants/Command'
import { debounce } from 'lodash'
import aesHelper from '@/utils/aesHelper'
import { useAuthStore } from '@/store/auth'
import accountStore from '@/store'
import { actionDebounce } from '@/utils/mpHelper'
import { safeTrack, applianceControlTrack } from '@/dataReport/dataReportUtil'
import { TrackType, trackEvent } from '@/dataReport/tracks'

const authStore = useAuthStore(accountStore)

const props = defineProps<{
  control: FridgeFreezerController.Control
}>()

const showLocalFlexSetting = computed(() => {
  return props.control.store.showLocalFlexSetting
})

const localFlexModes = computed(() => props.control.store.localFlexModes)
const localMode = computed(() => props.control.store.localMode)
const isSmartHygieneLite = computed(() => props.control.store.isSmartHygieneLite)

const brand = props.control.store.detail?.brand as string
/**
 * 确认更新变温功能
 */
const confirmFlex = actionDebounce({
  call: async () => {
    safeTrack(() => {
      let trackKey = 'FridgeFreezer.FlexCompartment.NewModeTitle.Text' //
      if (showLocalFlexSetting.value.type == 1) {
        trackKey = 'FridgeFreezer.FlexCompartment.ReplaceTitle.Text'
      }
      trackEvent(
        trackKey,
        { localMode: localMode.value, showLocalFlexSettingType: showLocalFlexSetting.value.type },
        TrackType.ApplianceDetail
      )
    })
    if (showLocalFlexSetting.value.type === 0) {
      if (localMode.value) {
        showLocalFlexSetting.value.type = 0
      } else {
        setNewLocalMode()
      }
    } else if (showLocalFlexSetting.value.type === 1) {
      showLocalFlexSetting.value.show = false
      setNewLocalMode()
    } else if (showLocalFlexSetting.value.type === 2) {
      showLocalFlexSetting.value.show = false
      props.control.store.updateFlexModalContent(showLocalFlexSetting.value)
    }
  },
})
/**
 * 取消吧变温功能
 */
function cancelFlex() {
  safeTrack(() => {
    let trackKey = 'FridgeFreezer.FlexCompartment.NewModeTitle.Cancel' //
    if (showLocalFlexSetting.value.type == 1) {
      trackKey = 'FridgeFreezer.FlexCompartment.ReplaceTitle.Cancel'
    }
    trackEvent(
      trackKey,
      { localMode: localMode.value, showLocalFlexSettingType: showLocalFlexSetting.value.type },
      TrackType.ApplianceDetail
    )
  })
  if (showLocalFlexSetting.value.type === 0 || showLocalFlexSetting.value.type === 1) {
    showLocalFlexSetting.value.show = false
    saveLocalFlexMode(false)
    props.control.store.updateFlexModalContent(showLocalFlexSetting.value)
  }
}

function saveLocalFlexMode(active: boolean) {
  let hasSameMode = false
  let arr = []
  let userId = aesHelper.decrypt(authStore.ciamId, authStore.key, authStore.iv)
  let value = showLocalFlexSetting.value.newLocalFlexMode
  value.active = active
  if (localFlexModes.value && localFlexModes.value.length > 0) {
    for (let i = 0; i < localFlexModes.value.length; i++) {
      if (
        localFlexModes.value[i].userId == userId &&
        props.control.store._datasource.haId == localFlexModes.value[i].haId
      ) {
        if (active) {
          hasSameMode = true
          arr.push(value)
          localFlexModes.value[i].value = arr
          break
        } else {
          for (let j = 0; j < localFlexModes.value[i].value.length; j++) {
            if (localFlexModes.value[i].value[j].id == value.id) {
              hasSameMode = true
              break
            }
          }
          if (!hasSameMode) {
            localFlexModes.value[i].value.push(value)
            hasSameMode = true
          }
          break
        }
      }
    }
  }
  if (!hasSameMode) {
    arr.push(value)
    localFlexModes.value.push({
      userId: userId,
      haId: props.control.store._datasource.haId,
      value: arr,
    })
  }
  uni.setStorageSync('fridgeFlexModes', localFlexModes.value)
}

/**
 * 设置新自定义模式到本地
 */
const setNewLocalMode = actionDebounce({
  call: async () => {
    uni.showLoading({
      title: '加载中...',
      mask: true,
    })
    let res = await setSetting(props.control.store._datasource.haId, FLEX_MODE_KEY, FLEX_MODE_CUSTOM)
    if (res.code == 0) {
      safeTrack(() => {
        trackEvent(
          'appliance_setting',
          { setting_key: FLEX_MODE_KEY, setting_value: FLEX_MODE_CUSTOM, successOrNot: true },
          TrackType.ApplianceDetail
        )
      })
      applianceControlTrack(
        () =>
          setSetting(
            props.control.store._datasource.haId,
            FLEX_KEY,
            showLocalFlexSetting.value.newLocalFlexMode.temperature
          ),
        'appliance_setting',
        { setting_key: FLEX_KEY, setting_value: showLocalFlexSetting.value.newLocalFlexMode.temperature },
        'Appliance.Settings.Fridge.LocalFlexSetting'
      )
      saveLocalFlexMode(true)
    } else {
      uni.showToast({
        title: '启用失败',
        icon: 'error',
      })

      safeTrack(() => {
        trackEvent(
          'appliance_setting',
          { setting_key: FLEX_MODE_KEY, setting_value: FLEX_MODE_CUSTOM, successOrNot: false },
          TrackType.ApplianceDetail
        )
      })
    }

    showLocalFlexSetting.value.show = false
    props.control.store.updateLocalMode(showLocalFlexSetting.value.newLocalFlexMode)
    uni.hideLoading()
  },
})
</script>

<style scoped lang="less"></style>
